package com.lemon.es;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;


import java.net.InetAddress;
import java.util.Map;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

public class SearchManager {

    @Test
    public void testPage() throws  Exception{
        System.out.println("===================1========================");
        this.searchMainByPage("lemon",1,10);//1 2
        //System.out.println("===================2========================");
        //this.searchMainByPage("",2,2);//3
    }


    public void searchMainByPage(String keyword,int pageNo,int pageSize) throws  Exception{

        Settings settings = Settings.EMPTY;// 告诉你采用的是默认配置
        TransportClient  transportClient  = new PreBuiltTransportClient(settings);
        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.75.128"),9300));
        // 1:查询所有
        //QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
//        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(keyword).defaultField("operator");
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        queryBuilder.must(QueryBuilders.matchPhraseQuery("operator",keyword));

        // 高亮设置
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.field("operator");
        highlightBuilder.postTags("</font>");


        SearchResponse response =  transportClient.prepareSearch("blog2").setTypes("content")
                //设置分页
                .setFrom((pageNo - 1)*pageSize) //设置查询起始位置
                .setSize(pageSize)//设置每页显示条数
                // 设置排序
//                .addSort("id", SortOrder.ASC)
                // 设置高亮
                .highlighter(highlightBuilder)
                // 设置查询条件
                .setQuery(queryBuilder).get();
        //3: 获取查询结果 TopDocs
        SearchHits searchHits =  response.getHits();
        System.out.println("一共命中到：" + searchHits.totalHits);
        //4: 遍历结果集
        for (SearchHit searchHit : searchHits) {
            System.out.println(searchHit.getSourceAsString());
            Map<String,Object> map = searchHit.getSourceAsMap();
            System.out.println(map.get("id"));
            //获取高亮元素的内容
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();

            Text[] titles = searchHit.getHighlightFields().get("operator").getFragments();
            if(titles!=null && titles.length>0) {
                StringBuffer buffer = new StringBuffer();
                for (Text title : titles) {
                    buffer.append(title.string());
                }
                System.out.println("高亮内容是:" + buffer.toString());
            }else{
                System.out.println(map.get("method"));
            }

            System.out.println(map.get("content"));
        }

        // 5: 关闭client
        transportClient.close();
    }




    @Test
    public void searchMain() throws  Exception{

        Settings settings = Settings.EMPTY;// 告诉你采用的是默认配置
        TransportClient  transportClient  = new PreBuiltTransportClient(settings);
        transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.75.128"),9300));
        // 设置查询条件
        // 1:查询所有
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        //2：根据关键词和指定的域去搜索，如果不指定域，就会从所有的域都去查找。
        // QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("solr").defaultField("title");
         //QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("我是找一本solr书籍").defaultField("title");
        //3：词条搜索，不会分词在进行搜索，搜索不支持多关键词和句子搜索。
        // QueryBuilder queryBuilder = QueryBuilders.termQuery("title","我是找一本solr书籍");
        //4：模糊搜索like。
         //QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("title","solr*");
        //5：id搜索。是只_id搜索，才id的搜索
        //QueryBuilder queryBuilder = QueryBuilders.termQuery("_id","3");
         //QueryBuilder queryBuilder =  QueryBuilders.idsQuery().addIds("3","1","2");
        //范围搜索
       /* RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("bookPrice");
        rangeQueryBuilder.from(100).includeLower(true);
        rangeQueryBuilder.to(100).includeLower(true);*/
        //6: 复合搜索
        // QueryBuilder queryBuilder =  QueryBuilders.boolQuery().must(queryBuilder).must(queryBuilder).must(queryBuilder)
        // 1:如果支持跨库搜索
        //transportClient.prepareSearch("blog2","blog3")
        //2:指定某个某个类型搜索
        SearchResponse response =  transportClient.prepareSearch("blog2").setTypes("content")
                // 设置排序
//                .addSort("id", SortOrder.ASC)
                // 设置查询条件
                .setQuery(queryBuilder).get();
        //3: 获取查询结果 TopDocs
        SearchHits searchHits =  response.getHits();
        System.out.println("一共命中到：" + searchHits.totalHits);
        //4: 遍历结果集
        for (SearchHit searchHit : searchHits) {
            System.out.println(searchHit.getSourceAsString());
            Map<String,Object> map = searchHit.getSourceAsMap();
            System.out.println(map.get("time"));
            System.out.println(map.get("method"));
            System.out.println(com.alibaba.fastjson.JSON.toJSONString(map.get("param")));
        }

        // 5: 关闭client
        transportClient.close();
    }










}
